package com.study.serialization.demo.hessian;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Objects;

public class HessianTest {

    public static void main(String[] args) {
        HessianEntity hessianEntity = new HessianEntity();
        hessianEntity.setA(1);
        hessianEntity.setB(2);
        byte[] result = serialize(hessianEntity);
        Object object = deserialize(result);
        System.out.println(object);
    }

    /**
     * hessian序列化
     *
     * @param <T>
     * @param object
     * @return
     * @throws Exception
     */

    public static <T> byte[] serialize(T object) {
        if (object == null) {
            throw new NullPointerException();
        }
        byte[] result = null;
        HessianOutput hessianOutput = null;
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            hessianOutput = new HessianOutput(os);
            //write本身是线程安全的
            hessianOutput.writeObject(object);
            result = os.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (Objects.nonNull(hessianOutput)) {
                try {
                    hessianOutput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * hessian反序列化
     *
     * @param bytes
     * @return
     * @throws Exception
     */

    @SuppressWarnings("unchecked")
    public static <T> T deserialize(byte[] bytes) {
        if (bytes == null) {
            throw new NullPointerException();
        }
        T result = null;
        HessianInput hessianInput = null;
        try (ByteArrayInputStream is = new ByteArrayInputStream(bytes)) {
            hessianInput = new HessianInput(is);
            result = (T) hessianInput.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (Objects.nonNull(hessianInput)) {
                hessianInput.close();
            }
        }
        return result;
    }
}
